#! /usr/bin/python3
# -*- coding: UTF-8 -*-

if __name__ == "__main__":
	raise Exception("不支持从这里调用")

__version__ = "1.0"
__all__ = []

import os

from com.mousechsh.business.app.wuziqi.MouseChshWuziqi import MouseChshWuziqi
from com.mousechsh.common.data.json.MouseChshJson import mousechsh_json_to_json
from com.mousechsh.common.io.file.MouseChshFile import mousechsh_file_read_text
from com.mousechsh.common.middle.http.MouseChshHttpHeader import mousechsh_http_header_accept_language_annotation
from com.mousechsh.common.middle.router.MouseChshHttpRouter import mousechsh_http_router_annotation

_mousechsh_wuziqi_group = {}


@mousechsh_http_router_annotation(method='GET', path='/')
@mousechsh_http_header_accept_language_annotation()
def index(url, request, response, *argsArr, **argsDict):
	response.get_header().set_content_type('html')
	response.set_body(mousechsh_file_read_text(os.path.join(os.path.dirname(__file__), 'MouseChshWuziqi.html')))

	@mousechsh_http_router_annotation(method='GET', path='/favicon.ico')
	@mousechsh_http_header_accept_language_annotation()
	def index(url, request, response, *argsArr, **argsDict):
		response.get_header().set_content_type('svg')
		response.set_body(mousechsh_file_read_text(os.path.join(
			os.path.dirname(__file__),
			'../../../common/middle/http/MouseChshFavicon.ico.svg'
		)))

	@mousechsh_http_router_annotation(method='POST', path='/<str pk>')
	@mousechsh_http_header_accept_language_annotation()
	def index(url, request, response, *argsArr, **argsDict):
		path = url.get_path()
		item = _mousechsh_wuziqi_group.get(path, None)
		if item is None:
			item = MouseChshWuziqi()
			_mousechsh_wuziqi_group[path] = item

		content = request.get_body()
		content = content.upper()
		if content == 'CLEAN':
			item.clean()
		elif len(content) == 4:
			item.set(content)
			item.check()

		response.get_header() \
			.set_content_type_('json') \
			.set_target_type_('group') \
			.set_target_id(request.get_header().get('Websocket-Group'))
		response.set_body(
			mousechsh_json_to_json({
				'': 'ROOM:' + path + '\n' + item.output(),
				'path': path,
				'total': len(_mousechsh_wuziqi_group),
				'table': item.table(),
				'history': item.history(),
				'result': item.result(),
				'current': item.current(),
				'last': item.last()
			})
		)
